package com.gagakuai.bind;

import com.gagakuai.session.Configuration;
import com.gagakuai.session.SqlSession;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/*
 * @program: settement
 * @description: 映射器注册
 * @author: houhong
 * @create: 2022-11-09 19:47
 */
public class MapperRegistry {

    private Configuration configuration;

    /*
     * 添加已经映射的mapper
     */
    private final Map<Class<?>, MapperProxyFactory<?>> knownMappers = new ConcurrentHashMap<>(16);

    public MapperRegistry(Configuration config) {
        this.configuration = config;
    }


    /*
     * @param session
     * @param mapperInterface
     * @return {@link T}
     * @Description //TODO 获取代理类
     * @Date 7:51 下午 2022/11/9
     */
    public <T> T getMapper(Class<T> mapperInterface, SqlSession session) {

        MapperProxyFactory<T> mapperProxyFactory = (MapperProxyFactory<T>) knownMappers.get(mapperInterface);

        if (mapperProxyFactory == null) {
            throw new BindingException("Type " + mapperInterface + " is not known to the MapperRegistry.");
        }

        try {
            return mapperProxyFactory.newInstance(session);
        } catch (Exception e) {
            throw new BindingException("Error getting mapper instance. Cause: " + e, e);
        }
    }

}